#ifndef COPPERPARTICLEDEVICE_H
#define COPPERPARTICLEDEVICE_H

#include <QObject>
#include <QTcpSocket>
#include <QTimer>
#include <QMap>
#include <QQueue>
#include <QMutex>
#include "types.h"
#include "ProtocolParser.h"

class CopperParticleDevice : public QObject
{
    Q_OBJECT

public:
    explicit CopperParticleDevice(QObject *parent = nullptr);
    ~CopperParticleDevice();

    // 设备连接管理
    bool connectToDevice(const QString &host, quint16 port);
    void disconnectFromDevice();
    bool isConnected() const;

    // 命令发送接口 - 异步队列方式
    bool sendDeviceCommand(DeviceProtocol::IPCCommand command,
                           const QVariantMap &params = QVariantMap());

    // 任务队列管理
    int getQueueSize() const;
    void clearCommandQueue();
    void addImmediateCommand(DeviceProtocol::IPCCommand command,
                             const QVariantMap &params = QVariantMap());

signals:
    void connected();
    void disconnected();
    void errorOccurred(const QString &error);
    void commandCompleted(DeviceProtocol::IPCCommand command, bool success, const QVariantMap &responseData);
    void statusNotificationReceived(const QVariantMap &statusData); // 状态通知信号
    void queryDataReceived(DeviceProtocol::IPCCommand command, const QVariantMap &data);// 查询数据直接接收信号
private slots:
    void onConnected();
    void onDisconnected();
    void onReadyRead();
    void onError(QAbstractSocket::SocketError error);
    void checkPendingRequests();
    void processCommandQueue();

private:
    QTcpSocket *m_socket;
    QTimer *m_requestCheckTimer;
    QTimer *m_queueProcessTimer;
    QMap<QString, PendingRequest> m_pendingRequests;
    ProtocolParser m_parser;
    QByteArray m_buffer;
    QList<PacketCache> m_packetCache;

    // 任务队列相关成员
    QQueue<DeviceCommandTask> m_highPriorityQueue;
    QQueue<DeviceCommandTask> m_normalQueue;
    mutable QMutex m_highPriorityMutex;
    mutable QMutex m_normalQueueMutex;
    bool m_processingCommand;
    DeviceCommandTask m_currentTask;

private:
    // 网络通信函数
    bool sendCommand(const QByteArray &command, int cn, bool needResponse = true);
    void resendRequest(const QString &qn);

    // 响应等待函数
    QByteArray waitForResponse(const QString &qn, int timeout = 3000);
    QVariantMap waitForResponseData(const QString &qn, int timeout = 3000);

    // 请求管理函数
    void removePendingRequest(const QString &qn);

    // 命令构建函数
    QByteArray buildCommandPacket(DeviceProtocol::IPCCommand command,
                                  const QVariantMap &params, QString &qn);
    QMap<QString, QString> convertToProtocolParams(DeviceProtocol::IPCCommand command,
                                                   const QVariantMap &params);
    int getCommandFlag(DeviceProtocol::IPCCommand command);

    // 响应处理函数
    bool processCommandResponse(DeviceProtocol::IPCCommand command,
                                const QMap<QString, QString> &responseParams,
                                QVariantMap *output);
    QString getExeRtnErrorMessage(int exeRtn);

    // 数据包处理函数
    void processSinglePacket(const QByteArray &packet);
    bool isDuplicatePacket(const QByteArray &packet);
    void cleanupPacketCache();
    bool sendDataAck(const QString &qn, int dataCn, const QString &no = QString());

    // 数据包解析函数
    QString extractCRCFromPacket(const QByteArray &packet);
    QString extractQNFromPacket(const QByteArray &packet);

    // 工具函数
    QString generateQN();

    // 任务队列相关函数
    void addCommandToQueue(const DeviceCommandTask &task);
    void processNextCommand();
    void completeCurrentCommand(bool success, const QVariantMap &responseData = QVariantMap());
    void retryCurrentCommand();
    bool sendImmediateCommand(const DeviceCommandTask &task);

private:
    bool parseExtendedStateData(const QString& stateStr, QVariantMap* output);
};

#endif // COPPERPARTICLEDEVICE_H
